import Koa from 'koa'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import cors from'@koa/cors'
import { Sequelize, DataTypes, where, Op } from 'sequelize'
const router = new Router()
const app = new Koa()
const port = 8080
app.use(cors())
app.use(bodyParser())
//建立数据库
//1. 初始化
let sequelize = new Sequelize('BookDB', 'root', '123456', {
    dialect: "mysql",
    host: 'localhost'
})
// 2. 创建表
let Booktb = sequelize.define('bookdb', {
    bookName: {
        type: DataTypes.STRING,
        allowNull: false
    },
    author: {
        type: DataTypes.STRING,
        allowNull: true
    },
    price: {
        type: DataTypes.INTEGER,
        allowNull: true
    }
})
// 3. 运行
// await sequelize.sync()

// -----------------------------------------------
//查找,过滤

router.get('/book', async (ctx, next) => {
    let keyword =ctx.request.query.keyword || ''
    let where =null
    if(keyword.trim()){
        where={
            [Op.or]:{
                bookName:{
                    [Op.like]:`%${keyword}%`
                },
                author:{
                    [Op.like]:`%${keyword}%`
                }
            }
        }
    }
    const obj =await Booktb.findAll({where})
    ctx.body = {
        code: 888,
        data: obj,
        msg: 'success'
    }
})
//单个对象
router.get('/book/:id', async (ctx, next) => {
    let id = ctx.params.id || 0
    let obj = await Booktb.findByPk(id)
    ctx.body = {
        code: 888,
        data: obj,
        msg: 'success'
    }
})
//新增
router.post('/book', async (ctx, next) => {
    let obj = ctx.request.body
    let res = await Booktb.create(obj)
    ctx.body = {
        code: 888,
        data: res,
        msg: 'success'
    }
})
//修改
router.put('/book/:id', async (ctx, next) => {
    let id = ctx.params.id||0
    let obj = ctx.request.body
    let res = await Booktb.update(obj, { where: { id } })
    ctx.body = {
        code: 888,
        data: res,
        msg: 'success'
    }
})
//删除
router.delete('/book/:id', async (ctx, next) => {
    let id = ctx.params.id ||0
    let res = await Booktb.destroy({where:{id}})
    ctx.body = {
        code: 888,
        data: res,
        msg: 'success'
    }
})
// -----------------------------------------------
app.use(router.routes())
app.listen(port, () => {
    console.log(`服务运行在：http://localhost:${port}`)
})
